function [res] = auto_import(arg)
% auto_import automatically imports into the datac control file all of the
% recognized protocols from all of the selected files.
% Driving tables:
%    Protocols: contains a list of the protocols to be imported.
%
% Output table:
%	file listing entries imported.
%   Program operates in two modes. Mode one tests the import and generates a list of 
% files and records that would be imported. Mode two does the full import
% 
%  5 Jan 2000 P. Manis
%
if(nargin < 1)
	arg = 't'; % for TEST
end;
switch(arg)
	case 't'
		disp('TESTING');
	case 'x'
		disp('EXECUTING');
	otherwise
		disp('TESTING!!!!!!!');
end;
res=[];

% Generate a place to store the data... using existing mechanisms...
   h = findobj('Tag', 'datac_main'); % check for pre-existing window
   if(isempty(h)) % if none, make one
      h = figure('Tag', 'datac_main', 'Name', 'UserData...', 'NumberTitle', 'off');
   end
   figure(h); % otherwise, select it

% read the control file
fimport=uigetfile('*.aut', 'Auto Import control File');
if(isempty(fimport))
	return;
end;

% the import file has the following structure:
% 
% infofile = information file to examine (IMP.infofile)
% proto =  protocols to import (IMP.proto)
% files = files to import (IMP.file)
% output = output file name (IMP.output)
% >go -> causes the import to be performed with the present information.
% additional lines with xxx = replace the previous values with new values;
% and >go will cause an import to continue..

imp_fields = {'infofile' 'proto' 'files' 'output'};
imp_data = {'' '' '' ''}; % initialize the data
imp_type = ['t', 'c', 't', 't'];	% imp type is either t (text) or c (cell array) 
IMP=[];
fh=fopen(fimport, 'r');
while(~feof(fh))
	x=fgetl(fh);
	x=unblank(x);
	if(~isempty(x) & ~all(isspace(x)))
		if(findstr(x, '>go'))
			IMP=load_struct(imp_fields, [imp_data]);
			disp(sprintf('\nPreparing to import from %s', IMP.files))
			res=import(IMP, arg);
		elseif (x(1) ~= '#') % that removes the comments
			[x, rem] = strtok(x, '='); % get the lhs of an argument
			x=unblank(x);
			k = strmatch(x, imp_fields);
			if(k > 0) % protocol is in the list
				rem = rem(3:length(rem)); 
				switch imp_type(k) % store the data according to the type that it is
				case 't'
					imp_data(k) = {rem}; % just the whole remainder of the string
				case 'c' % cell array = do it element wise
					z=[];
					while(~isempty(rem))
						[y, rem] = strtok(rem);
						z=strvcat(z, y);
					end;
					imp_data(k) = {z};
				otherwise
				end;
			else
				disp(sprintf(' ***** %s is unrecognized field to fill', x))
			end;
		end;
	end;
	if(feof(fh))
		break;
	end;
end;
return;




function [control] = import(IMP, arg); % IMP is the structure..., arg is the flag...

% read a base information file - contains the formatted information to be automatically added to the list
% filename Celltype  commentary 
%
control=[];
fh=fopen(char(IMP.infofile), 'r'); % read the information file (this is info that is added to the structure.
if(isempty(fh))
	disp(sprintf('Unable to read infofile: %s', char(IMP.infofile)))
	return;
end;
% read the "inclusion" line. The entries in this line define the 
% fields that are defined in the columns beneath.
% each field is separated by a '|', just like the rest of the file
% We then generate a new INCLUDE structure to hold the results
%

inames = [];
x=fgetl(fh); % read the first line
INCLUDE=[];
while(~isempty(x)) % parse the line
	[fn, x] = strtok(x, '|');
	if(~isempty(fn)) % that's the name of the field
		unblank(fn);
		if(~isfield(INCLUDE, fn))
				INCLUDE = setfield(INCLUDE, fn, []);
			fprintf('Duplicate field: %s', fn); % print warning message
		end;
	end;
end;
INCLUDE
return;

i=0;
INCLUDE(1).fname={''};
INCLUDE(1).ctype={''};
INCLUDE(1).comment={''};
INCLUDE(1).pnd={''}; % postnatal days
INCLUDE(1).div={''}; % days in vitro
INCLUDE(1).E_C={''}; % experimental or control
INCLUDE(1).G1={''}; % group 1
INCLUDE(1).G2={''}; % group 2 (for two factor analysis...)
INCLUDE(1).vgain={''}; % voltage gain 
INCLUDE(1).stim={''}; % stimulus delivery times (for stim_time)
INCLUDE(1).fpan={''}; % analysis times (for psp_time)

return;  % just testing.

while(~feof(fh))
	i=i+1;
	x=fgetl(fh);
	if(~isempty(x))
		[fn, x] = strtok(x, '|');
		[ct, x] = strtok(x, '|');
		[co, x] = strtok(x, '|');
		[pnd, x] = strtok(x, '|');
		[div, x] = strtok(x, '|');
		[ec, x] = strtok(x, '|');
		[g1, x] = strtok(x, '|');
		[g2, x] = strtok(x, '|');
		[vgain, x] = strtok(x, '/');
		INCLUDE(i).fname=unblank(fn);
		INCLUDE(i).ctype={ct};
		INCLUDE(i).pnd = {pnd};
		INCLUDE(i).div = {div};
		INCLUDE(i).comment={co};
		INCLUDE(i).E_C = {ec};
		INCLUDE(i).G1={g1};
		INCLUDE(i).G2={g2};
		INCLUDE(i).vgain = {vgain};
		[st1, x] = strtok(x, '|');
		if(~isempty(st1)) % this means we had a value, so we expect to fill the rest of the fields
			INCLUDE(i).stim   = [str2num(st1)];
			[fpt, x] = strtok(x, '|');
			INCLUDE(i).fpan = [str2num(fpt)];
		end;
	end;
end;
fclose(fh);
% make protocol list USEFUL
%p=sprintf('strvcat(%s)', IMP.proto);
%pq=eval(p);
	
a=ls(sprintf('%s', IMP.files)); % get the directory
[path,name,ext,ver] = fileparts(IMP.files); % just to get the path that was specified
rem=deblank(a);
nf = 0;
np=0;
used_proto='';
unused_proto='';
while (~isempty(rem))
	[b, rem]=strtok(rem);
	if(isempty(b))
		break; % that means we are done
	end;
	c=deblank(b);
	if(c(length(c))~=':') % signals a directory, skip directories
		n=lower(b);
		truefile = c; % fullfile(path, c);
		[DFILE, data, err] = datac2mat(truefile, []); % just read the header - empty RL list
		if(err == 1) 
			disp(sprintf('Unable to open file? %s', truefile))
		elseif(err == 2) 
			disp(sprintf(' ***** %s is an Empty file', truefile))
		else
			% now read the note file and paste information up on display
			[path, name, next, ver] = fileparts(truefile);
			uext=upper(ext);
			if(strcmp(uext, ext))
				next='.NOT';
			else
				next = '.not';
			end;
			notefile = fullfile(path, [name, next]);
			disp(sprintf('Parsing Notefile: %s', notefile))
			[NOTEFILE, note_err] = note_read(notefile);
			rz = find([NOTEFILE.frec] == 0);
			if(~isempty(rz))
				NOTEFILE(rz).frec = 1; % fix notefile records that are set to 0
			end;
			for i=1:length(NOTEFILE)
				if(strmatch(NOTEFILE(i).proto, IMP.proto, 'EXACT') > 0) % protocol is in the list
					if(strcmp(arg,'x')) % only if we are executing do we run this section
						CONTROL=getuserdata;
						[DFILE, data, err] = datac2mat(truefile, [NOTEFILE(i).frec]); % pick off the first record for scaling factors
						save_to_control(CONTROL, DFILE, NOTEFILE, i, INCLUDE); % basic - just the selected record in the list...
					end;
					np=np+1; % count protocols
					disp(sprintf('Protocol: %s', NOTEFILE(i).proto))
					if(isempty(strmatch(NOTEFILE(i).proto, used_proto, 'EXACT')))
						used_proto=strvcat(used_proto, NOTEFILE(i).proto); % add it to the list
					end;
				else
					disp(sprintf('Unused Protocol: %s', NOTEFILE(i).proto))
					if(isempty(strmatch(NOTEFILE(i).proto, unused_proto, 'EXACT')))
						unused_proto=strvcat(unused_proto, NOTEFILE(i).proto);
					end;
				end;
				disp(sprintf('Analyzed file: %s\n', DFILE.filename))
				nf=nf+1;
			end;
		end;
	else
		disp(sprintf('In directory %s \n', b))
		thisdir = b(1:length(b)-1);
	end;
end;
control=getuserdata; % that's the data; 
if(strcmp(arg,'x'))
	save(char(IMP.output), 'control'); % save it to a file...
	disp(sprintf('\nWriting mat file: %s', char(IMP.output)))
	end;

if(nf==0)
	disp('No files Read')
else
	disp(sprintf('%d Files read, %d protocols entered', nf, np))
	disp('Protocols USED: ')
	used_proto
	disp('Protocols UNUSED: ')
	unused_proto
end
return;


function [ctl, err] = save_to_control(CONTROL, DFILE, NOTEFILE, nf, INCLUDE)
% update the list/control from the current input file...
%

CC_Protos={'cciv' 'hyp' 'hyp2' 'tc', 'hyps', 'buildup', 'highfire', 'shkio', 'shktest', 'pharm', 'shock', 'io', 'iv'}; % define all current clamp protocols

n=size(CONTROL);
sf=n(2)+1;
protocol=deblank(char(NOTEFILE(nf).proto)); % use this one.
disp(sprintf('Storing %s in position %d', protocol, sf))

CONTROL(sf).seqname = make_sequence(char(DFILE.filename), DFILE.frec);
CONTROL(sf).filename = strcat(char(DFILE.filename), char(DFILE.ext));
CONTROL(sf).path = append_backslash(DFILE.path);
CONTROL(sf).quality = 'good';
CONTROL(sf).mode = 'VC';
CONTROL(sf).protocol = protocol; % extract the protocol that we ran
if(strmatch(CONTROL(sf).protocol, CC_Protos, 'EXACT'))
	CONTROL(sf).mode='CC';
end;

CONTROL(sf).solution = '';
CONTROL(sf).pnd = 0;
CONTROL(sf).div = 0;
CONTROL(sf).E_C = 0;
CONTROL(sf).G1 = 0;
CONTROL(sf).G2 = 0;

CONTROL(sf).sequence = NOTEFILE(nf).seq;  % extract the sequence from the notefile
CONTROL(sf).recbeg = NOTEFILE(nf).frec;
CONTROL(sf).recend = NOTEFILE(nf).lrec;
CONTROL(sf).reclist = '';
CONTROL(sf).skip = 1;
CONTROL(sf).groupavg = 1;
if(~check_field(CONTROL(sf), 'CellType'))
	CONTROL(sf).CellType = '?';
end;

if(~check_field(CONTROL(sf), 'Commentary'))
	CONTROL(sf).Commentary = ' ';
end   

% try to set stuff from the input INCLUDE table 
i=strmatch(CONTROL(sf).filename, char(INCLUDE.fname));
CONTROL(sf).vgain = 10; % set as if for voltage clamp
if(strmatch(CONTROL(sf).protocol, CC_Protos, 'EXACT'))
   CONTROL(sf).vgain=1; % for current clamp protocols
end;

if(i > 0)
	disp('Filling fields\n')
	CONTROL(sf).CellType=char(INCLUDE(i).ctype);
	CONTROL(sf).Commentary=char(INCLUDE(i).comment);
	CONTROL(sf).pnd=str2num(char(INCLUDE(i).pnd));
	CONTROL(sf).E_C = char(INCLUDE(i).E_C);
	CONTROL(sf).G1 = str2num(char(INCLUDE(i).G1));
	CONTROL(sf).G2 = str2num(char(INCLUDE(i).G2));	
	CONTROL(sf).vgain = str2num(char(INCLUDE(i).vgain));
	CONTROL(sf).stim_time = INCLUDE(i).stim;
	CONTROL(sf).psp_time = INCLUDE(i).fpan;
end;

CONTROL(sf).igain = 1;
CONTROL(sf).iunits = 'nA';
CONTROL(sf).wgain = 1;
CONTROL(sf).tbeg = 0;
CONTROL(sf).tend = 200;
CONTROL(sf).thresh = 0;
CONTROL(sf).jpot = 0;
CONTROL(sf).access = 0;
CONTROL(sf).comp = 0;
CONTROL(sf).alignwin = 0;
CONTROL(sf).leakwin = 2;
if(strmatch(protocol, {'iva' 'qinactp2'}))
	CONTROL(sf).leakwin = 3;
end;
CONTROL(sf).transwin = 2;
CONTROL(sf).transwdur = 45;
CONTROL(sf).deadwin = 0.1;
nstep=length(DFILE.steps);
CONTROL(sf).durho = 0;
CONTROL(sf).durs1 = 0; CONTROL(sf).durs2 = 0; CONTROL(sf).durs3 = 0;
if(nstep > 0)
	CONTROL(sf).durho = number_arg(DFILE.steps(1));
	if(nstep > 1)
		CONTROL(sf).durs1 = number_arg(DFILE.steps(2)) - number_arg(CONTROL(sf).durho);
	end
	if(nstep > 2) CONTROL(sf).durs2 = number_arg(DFILE.steps(3)) - number_arg(CONTROL(sf).durs1); end
	if(nstep > 3) CONTROL(sf).durs3 = number_arg(DFILE.steps(4)) - number_arg(CONTROL(sf).durs2); end
end
CONTROL(sf).diff = 0;
CONTROL(sf).file = '';
CONTROL(sf).altmode = 0;
CONTROL(sf).bactn = 1;
CONTROL(sf).cycle = 1000;
CONTROL(sf).bstart = 0;
CONTROL(sf).bend = 2;
   
CONTROL(sf).vlmax = -60;
CONTROL(sf).vlmin = -90;
CONTROL(sf).leakt = 11;
CONTROL(sf).Gin = 0;
CONTROL(sf).Rin = 0;
CONTROL(sf).iHold = 0;
CONTROL(sf).Vm0 = 0;
CONTROL(sf).Rmp = 0;
ch = clock;
CONTROL(sf).entrydate = strcat(date, sprintf(' %02.0f:%02.0f:%02.0f', ch(4), ch(5), ch(6)));
CONTROL(sf).lastchanged = strcat(date, sprintf(' %02.0f:%02.0f:%02.0f', ch(4), ch(5), ch(6)));
CONTROL(sf).subtract = 'no';
CONTROL(sf).linkfile = '';
CONTROL(sf).sub_frec = 1;
CONTROL(sf).sub_lrec = 1;
CONTROL(sf).sub_access = 0;
CONTROL(sf).sub_comp = 0;
CONTROL(sf).sub_igain = 1;
if(~check_field(CONTROL(sf), 'stim_time'))
	CONTROL(sf).stim_time = [];
end;
if(~check_field(CONTROL(sf), 'psp_time'))
	CONTROL(sf).psp_time  = [];
end;

CONTROL = set_defaults(CONTROL, sf, protocol, DFILE); % set the rest of the defaults

if(~isempty(NOTEFILE))
	CONTROL(sf).NOTEFILE=NOTEFILE; % install the current notefile.
end;
   
% make the data available.....
setuserdata(CONTROL)   
return;


function [control] = set_defaults(ctl, sel, proto, DFILE);
% set_defaults sets the PROTOCOl specific default values.

control = ctl; % first copy it over...
switch(proto)
case {'qinactp2', 'qinactp3'} % set OO patch defaults...
	control(sel).vgain=1;
	control(sel).igain=DFILE.gain(1,2);
	control(sel).jpot=-12; % kgluc
	control(sel).mode='VC';
	control(sel).durho=5;
	control(sel).durs1=100; % defaults for qinactp2/p3
	control(sel).durs2=300;
	control(sel).durs3=100;
	control(sel).leakwin=3;
 
case 'iv' % set OO patch /WC IV defaults...
	control(sel).vgain=1;
	control(sel).igain=DFILE.gain(1,2);
	control(sel).jpot=-12; % kgluc
	control(sel).mode='VC';
	control(sel).durho=10;
	control(sel).durs1=100; % defaults for qinactp2/p3
	control(sel).durs2=0;
	control(sel).durs3=0;
	control(sel).leakwin=2;


case 'pativ' % set Cell-attached patch defaults...
	control(sel).vgain=-1;
	control(sel).igain=-DFILE.gain(1,2); % just reverse the gain factor...
	control(sel).jpot=-60; % kgluc
	control(sel).mode='VC';
	control(sel).durho=10;
	control(sel).durs1=300; % defaults for qinactp2/p3
	control(sel).durs2=0;
	control(sel).durs3=0;
	control(sel).leakwin=0;
	control(sel).transwin=0;

case 'patqp2' % set Cell-attached patch defaults...
	control(sel).vgain=-1;
	control(sel).igain=-DFILE.gain(1,2); % just reverse the gain factor...
	control(sel).jpot=-60; % kgluc
	control(sel).mode='VC';
	control(sel).durho=5;
	control(sel).durs1=100; % defaults for qinactp2/p3
	control(sel).durs2=300;
	control(sel).durs3=100;
	control(sel).leakwin=3;
	control(sel).transwin=2;

case {'cciv', 'refract', 'entrain', 'hyp', 'hyp2'} % set Current-clamp defaults (like cciv)...
	control(sel).vgain=1; % DFILE.gain(1,1);
	control(sel).igain=1;
	control(sel).jpot=-12; % kgluc
	control(sel).mode='CC';
	control(sel).durho=10;
	control(sel).durs1=100;
	control(sel).durs2=0;
	control(sel).durs3=0;

case 'shkio' % shock IO function latency measurements
	control(sel).vgain=200; % DFILE.gain(1,1);
	control(sel).igain=1;
	control(sel).jpot=0; % kgluc
	control(sel).mode='CC';
	if(isempty(control(sel).psp_time))
		control(sel).psp_time = [6 15 35 56 65 85];
		control(sel).stim_time = [5 55];
	end;
	
case {'shktest', 'pharm'}
	control(sel).vgain=200; % DFILE.gain(1,1);
	control(sel).igain=1;
	control(sel).jpot=0; % kgluc
	control(sel).mode='CC';
	if(isempty(control(sel).psp_time))
		control(sel).psp_time = [6 15 35 56 65 85];
		control(sel).stim_time = [5 55];
    end;
otherwise
end

return;
